#include<sys/socket.h>
#include<netinet/in.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<arpa/inet.h>
#include<string.h>
#include<pthread.h>
#define PORT 8888
#define BUFFER_SIZE 1024

void*sendmessage(void*arg){
int sock=*(int*)arg;
char buffer[BUFFER_SIZE]={0};
while(1){
    fgets(buffer,BUFFER_SIZE,stdin);
    buffer[strcspn(buffer,"\n")]=0;
    if(strlen(buffer)){
        send(sock,buffer,strlen(buffer),0);
    }
}
}


void *recmessage(void*arg){
int sock=*(int*)arg;
char buffer[BUFFER_SIZE]={0};
while(1){
    int len=read(sock,buffer,BUFFER_SIZE);
    if(len<0){
        perror(".....");
    }
    buffer[len]='\0';
    printf("收到广播信息%s\n",buffer);
    memset(buffer,0,sizeof(buffer));

}
return NULL;
}



int main(){
    int sock=0;
    char hello[128];
    struct sockaddr_in server_addr;
    server_addr.sin_family=AF_INET;
    server_addr.sin_port=htons(PORT);
    
    sock=socket(AF_INET,SOCK_STREAM,0);

    if(sock==-1)
{
    perror("socket create failed\n");
    exit(EXIT_FAILURE);
}

//daima  127.0.0.1
    int rc=inet_pton(AF_INET,"127.0.0.1",&server_addr.sin_addr);
    if(rc<0){
    perror("inet_pton error!\n");
    return -1;
    }
    rc=connect(sock,(struct sockaddr*)&server_addr,sizeof(server_addr));
    if(rc<0){
    perror("connect fairy!\n");
    return -1;
    }
    printf("connect success!\n");

    snprintf(hello,sizeof(hello),"客户%d上线了!",sock);
    send(sock,hello,strlen(hello),0);
    pthread_t send_thread,recieve_thread;
    pthread_create(&send_thread,NULL,sendmessage,&sock);
    pthread_create(&recieve_thread,NULL,recmessage,&sock);
    pthread_join(send_thread,NULL);




}